<template>
  <!-- 制造商/客户表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="800px"
    draggable
    align-center
    :close-on-press-escape="false"
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      :inline="true"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="制造商编号" prop="makerCode" style="width: 100%">
            <el-input
              v-model="formData.makerCode"
              placeholder="请输入制造商编号"
              style="width: 95%"
            /> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="制造商名称" prop="makerName" style="width: 100%">
            <el-input
              v-model="formData.makerName"
              placeholder="请输入制造商名称"
              style="width: 95%"
            /> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="邮政编码" prop="zipCode" style="width: 100%">
            <el-input
              v-model="formData.zipCode"
              placeholder="请输入邮政编码"
              style="width: 95%"
              clearable
            /> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactName1" style="width: 100%">
            <el-input
              v-model="formData.contactName1"
              placeholder="请输入联系人"
              style="width: 95%"
              clearable
            /> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" style="width: 100%">
            <el-input
              v-model="formData.contactPhone1"
              placeholder="请输入联系电话"
              style="width: 95%"
              clearable
            /> </el-form-item
        ></el-col>
        <el-col :span="12"
          ><el-form-item label="备注" prop="remarks" style="width: 100%">
            <el-input
              v-model="formData.remarks"
              type="textarea"
              placeholder="请输入备注"
              style="width: 95%"
            /> </el-form-item
        ></el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="8">
          <el-form-item label="国家" prop="country">
            <el-input
              v-model="formData.country"
              placeholder="请输入国家"
              style="width: 250px"
            /> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="地区" prop="areas">
            <el-cascader
              placeholder="请输入地区"
              :options="areaOptions"
              v-model="formData.area"
              @change="areaHandleChange"
              style="width: 250px"
            /> </el-form-item
        ></el-col> -->
      </el-row>
      <!-- <el-row>
        <el-col :span="24"
          ><el-form-item label="详细地址" prop="address">
            <el-input
              v-model="formData.address"
              type="textarea"
              :rows="1"
              maxlength="255"
              style="width: 950px"
              placeholder="请输入详细地址"
            /> </el-form-item
        ></el-col>
      </el-row> -->

      <!-- <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <h4 class="mb-[20px] mt-[20px]">联系人</h4>
        <el-button type="success" plain @click="handleContactAdd">
          <i-ep-plus />
          添加行</el-button
        >
      </div>

      <div class="formTable">
        <el-table
          :data="formData.details"
          style="width: 100%"
          :key="Math.random"
          max-height="375px"
          border
        >
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="90"
          />
          <el-table-column
            label="姓名"
            align="center"
            props="contactName"
            width="160"
          >
            <template #default="{ $index, row }">
              <el-form-item
                :prop="'details.' + $index + '.contactName'"
                :rules="rules.contactName"
              >
                <el-input
                  v-model="row.contactName"
                  placeholder="请输入联系人姓名"
                  style="width: 140px"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="电话"
            align="center"
            props="contactPhone"
            width="160"
          >
            <template #default="{ $index, row }">
              <el-form-item
                :prop="'details.' + $index + '.contactPhone'"
                :rules="rules.contactPhone"
              >
                <el-input
                  v-model="row.contactPhone"
                  placeholder="请输入联系人电话"
                  style="width: 140px"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="邮箱"
            align="center"
            props="contactMail"
            width="280"
          >
            <template #default="{ $index, row }">
              <el-form-item :prop="'details.' + $index + '.contactMail'">
                <el-input
                  v-model="row.contactMail"
                  placeholder="请输入联系人邮箱"
                  style="width: 260px"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="地址"
            align="center"
            props="contactAddress"
            width="250"
          >
            <template #default="{ $index, row }">
              <el-form-item :prop="'details.' + $index + '.contactAddress'">
                <el-input
                  v-model="row.contactAddress"
                  placeholder="请输入联系人地址"
                  style="width: 230px"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            label="操作"
            v-if="!props.isReadonly"
          >
            <template #default="scope">
              <el-button
                :disabled="formData.details.length < 2"
                type="danger"
                link
                @click.stop="handleContactDelete(scope.$index)"
                ><i-ep-delete />
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div> -->
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { regionData, codeToText, pcaTextArr } from "element-china-area-data";
import { useDictionary } from "@/utils/useTable";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EAMABDSSETMAKEREDIT",
  inheritAttrs: false,
});

let defaultTabValue = ref(1);
// 需要联动的数据
const areaOptions = ref(pcaTextArr);
// 需要回显的数据
const selectedOptions = ref([]);
const materials = ref([]);
// 变更事件
function areaHandleChange(value: any) {
  if (value) {
    // 赋值操作
    formData.province = value[0];
    formData.city = value[1];
    formData.region = value[2];
  }
}

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetKind: {
    type: Number,
    default: null,
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);
watch(
  () => props.assetKind,
  (newVal: number) => {},
  {
    immediate: true,
  }
);
const checkMobile = (rule: any, value: any, callback: any) => {
  if (value != "") {
    let reg11 = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (reg11.test(value)) {
      callback();
    } else {
      callback(new Error("请输入正确格式电话号"));
    }
  } else {
    callback();
  }
};

const phoneRepeatCheck = (rule: any, value: any, callback: any) => {
  if (value) {
    const details = formData.details;
    var findCnt = 0;
    for (let i = 0; i < details.length; i++) {
      const element = details[i];
      if (element.contactPhone === value) {
        findCnt++;
      }
    }
    if (findCnt > 1) {
      return callback(new Error("此手机号已录入"));
    } else {
      callback();
    }
  }
};

const rules = reactive({
  makerCode: [
    { required: true, message: "请输入制造商编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  makerName: [
    { required: true, message: "请输入制造商名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  organizationId: [
    { required: true, message: "请选择所属公司", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],

  country: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  area: [{ required: true, message: "请选择地区", trigger: "change" }],
  zipCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  contactName: [
    { required: true, message: "请输入联系人姓名", trigger: "blur" },
  ],
  contactPhone: [
    { required: true, message: "请输入联系人电话", trigger: "blur" },
    { validator: checkMobile, trigger: "blur" },
    { validator: phoneRepeatCheck, trigger: "blur" },
  ],
  contactPhone1: [
    // { required: true, message: "请输入联系人电话", trigger: "blur" },
    { validator: checkMobile, trigger: "blur" },
    { validator: phoneRepeatCheck, trigger: "blur" },
  ],
  materialId: [
    { required: true, message: "请选择物料", trigger: "change" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  assetKind: props.assetKind,
  id: "",
  makerCode: "",
  makerName: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  address: "",
  country: "",
  province: "",
  city: "",
  region: "",
  street: "",
  houseCode: "",
  zipCode: "",
  contactName1: "",
  contactPhone1: "",
  contactName2: "",
  contactPhone2: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  deleted: "",
  area: [],
  details: [],
  products: [],
});

const contact = {
  id: "",
  partnerId: "",
  contactName: "",
  contactPhone: "",
  contactMail: "",
  contactAddress: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
};

let corpList = ref([]);

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        assetKind,
        id,
        makerCode,
        makerName,
        organizationId,
        organizationCode,
        organizationName,
        address,
        country,
        province,
        city,
        region,
        street,
        houseCode,
        zipCode,
        contactName1,
        contactPhone1,
        contactName2,
        contactPhone2,
        details,
        products,
        remarks,
        createTime,
        createdUserId,
        lastUpdateTime,
        lastUpdatedUserId,
        deleted,
      } = newVal;
      Object.assign(formData, {
        assetKind,
        id,
        makerCode,
        makerName,
        organizationId,
        organizationCode,
        organizationName,
        address,
        country,
        province,
        city,
        region,
        street,
        houseCode,
        zipCode,
        contactName1,
        contactPhone1,
        contactName2,
        contactPhone2,
        details,
        products,
        remarks,
        createTime,
        createdUserId,
        lastUpdateTime,
        lastUpdatedUserId,
        deleted,
      });
      formData.area.push(province);
      formData.area.push(city);
      formData.area.push(region);
    } else {
      formData.assetKind = props.assetKind;
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.assetKind = props.assetKind;
  formData.makerCode = "";
  formData.makerName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.address = "";
  formData.country = "";
  formData.province = "";
  formData.city = "";
  formData.region = "";
  formData.street = "";
  formData.houseCode = "";
  formData.zipCode = "";
  formData.contactName1 = "";
  formData.contactPhone1 = "";
  formData.contactName2 = "";
  formData.contactPhone2 = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.deleted = "";
  formData.area = [];
  formData.details = [];
  formData.products = [];
}

const loading = ref(false);

/** 联系人添加行 */
const handleContactAdd = () => {
  console.log(11);

  let sondata = JSON.parse(JSON.stringify(contact));
  formData.details.push(sondata);
};

/** 联系人删除行 */
const isValidated = ref(false);
const handleContactDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

/** 制造商/客户保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/eammaker/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style lang="scss" scoped>
:deep(.el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.el-table .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.el-table) {
  // .cell.el-tooltip {
  //   padding: 0 15px;
  // }

  // .el-table__body td.el-table__cell {
  //   padding: 20;
  // }
  // .cell.el-tooltip {
  //   padding: 5px;
  // }
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}
</style>
